package view.GUI.adminView.coreData.people.staff;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.stage.Stage;

import org.controlsfx.dialog.Dialogs;
import org.controlsfx.validation.Validator;

import enums.GUIText;
import enums.Message;
import enums.Status;
import model.data.interfaces.IFinishable;
import model.data.tableModel.person.Staff;
import view.GUI.adminView.coreData.people.EditBox;
import view.GUI.mainView.MainView;
import view.Validator.MyValidationSupport;


public class EditStaff extends StaffView{

	private EditBox editbox;
	
	public EditStaff(MainView instance) {
		super(true, GUIText.EDITSTAFF, instance);
		editbox = new EditBox(valSup, GUIText.STAFF, owner.getStaff());
		valSup.registerValidator(editbox.getComboBox(), true, Validator.createEmptyValidator(Message.THISISNEEDEDINPUT.toString()));
		
		editbox.getComboBox().getSelectionModel().selectedItemProperty().addListener(new ChangeListener<IFinishable>(){

			@Override
			public void changed(ObservableValue<? extends IFinishable> observable, IFinishable oldValue, IFinishable newValue) {
				btnSave.setDisable(MyValidationSupport.isNodeToDisable(valSup));
				lblShowNick.setText(((Staff) newValue).getNickname());
			}

		});
		int columnCounter = 0;
		for(Node n: editbox.getNodes()){
			super.addNode(n, columnCounter++, 0);
		}
		btnSave.setDisable(MyValidationSupport.isNodeToDisable(valSup));
		try {
			start(new Stage());
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	protected boolean save() {
		Staff s = (Staff) editbox.getComboBox().getSelectionModel().getSelectedItem();
		if(editbox.isDeleteSelected()){
			
			s.setStatus(Status.INACTIVE);
			owner.deleteStaff(s);
			s.writeUpdateToDB();
			return true;
		} else{
			// if passwords were entered and are equal
			if(txtPW.getText() != null && txtValidatePW.getText() != null && !"".equals(txtPW.getText()) && !"".equals(txtValidatePW.getText())){
				if(txtPW.getText().equals(txtValidatePW.getText())){
					owner.setNewPassword(s, txtPW.getText());
					s.writeUpdateToDB();
					return true;
				} else{
					Dialogs.create()
							.message(Message.WRONGPW.toString())
							.showError();
					return false;
				}
			} else{
				Dialogs.create()
						.message(Message.MSGMISSINGINFO.toString())
						.showError();
				return false;
			}
		}
	}
}
